package com.ve.bluetooth;

import android.bluetooth.BluetoothSocket;
import android.util.Log;

import com.ve.downloader.BufferSerial;
import com.ve.downloader.utils.HexUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

public class BluetoothSerialAdapter extends BufferSerial {
    private static final String TAG = BluetoothSerialAdapter.class.getSimpleName();
    private final BluetoothService ser;
    private InputStream inputStream;
    private OutputStream outputStream;

    public BluetoothSerialAdapter(BluetoothService service) {
        this.ser=service;
        try {
            BluetoothSocket socket = service.getBluetoothSocket();
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void setBaudrate(int baudrate) {

    }

    @Override
    public int getBaudrate() {
        return 9600;
    }

    @Override
    public int read(byte[] buff, int size) {
        try {
            if (inputStream.available() > 0) {
                int read = inputStream.read(buff, 0, size);
                Log.d(TAG, "read: " + HexUtils.toString(Arrays.copyOfRange(buff, 0, read)));
                return read;
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "read: 0");
        }
        return 0;

    }

    @Override
    public void write(byte[] bytes) throws IOException {
        outputStream.write(bytes);

    }

    @Override
    public void setParity(boolean parity) {

    }

    @Override
    public void close() {
        ser.disconnect();
    }
}
